#!encoding: utf-8
from django  import forms
from goodies.models import Customer
from django.forms.widgets import RadioSelect, PasswordInput, Select, TextInput, Textarea
from haystack.forms import SearchForm, ModelSearchForm 
from haystack.query import SearchQuerySet
from mptt.forms import TreeNodeChoiceField 
from goodies.models import Category

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit,Button,Field, HTML, Div, MultiField
from crispy_forms.bootstrap import  PrependedText



rd = {}
rd["email"] = {'required':u'Пожалуйста, укажите email','invalid':u'Email должени быть валиден'}
rd["fio" ] = {'required':u'Пожалуйста, укажите ваши инициалы'}
rd["phone"] = {'required':u'Пожалуйста, укажите телефон'}
rd["passw"] = {'required':u'Пожалуйста, укажите пароль'}
rd['address']={'required':u'Пожалуйста, укажите адрес'}
rd['submit'] ={'required':u'Вы дожны согласиться с правилами'}

rd['number'] ={'invalid':u"Введите число/числа правильно!"}

w = forms.TextInput(attrs={'style':'width:400px;'})
l_w = forms.Textarea(attrs={'style':'width:400px;height:50px'})



class OrderForm(forms.Form):
    payment_choice = (
      (0,"наличными"      ),
      (1,"безналичными"   ),
      (2,"через сберкассу"))

    fio      =  forms.CharField(     label = u'ФИО',     error_messages = rd['fio'],    widget=w)
    email    =  forms.EmailField(    label = u'Почта',   error_messages = rd['email'],   widget=w)
    phone    =  forms.CharField(     label = u'Телефон', error_messages = rd['phone'],   widget=w)
    address  =  forms.CharField(     label = u'Адрес',   error_messages = rd['address'], widget=l_w)
    payment  =  forms.ChoiceField(   label = u'Укажите способ оплаты',   choices=payment_choice)
    comment  =  forms.CharField(     label = u'Комментарий',required=False,           widget=l_w)

    def submit(self,customer_id):
        c = Customer.objects.get(pk=customer_id)
        c.fio      = self.cleaned_data.get('fio')
        c.email    = self.cleaned_data.get('email')
        c.phone    = self.cleaned_data.get('phone')
        c.address  = self.cleaned_data.get('address')
        c.pay_type = self.cleaned_data.get('payment')
        c.comment  = self.cleaned_data.get('comment')
        c.save()
        return c

    def populate(self,user,child_call=0):
        i = {
          'fio'    :user.fio,
          'email'  :user.email,
          'phone'  :user.phone,
          'address':user.address,
          'payment':user.pay_type,
          'comment':user.comment}
        if child_call: return i

        self.initial = i
        return True

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_id = 'id-OrderForm'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = '/personal/'
        self.helper.add_input(Submit('submit', 'Подтвердить'))
        super(OrderForm, self).__init__(*args, **kwargs)



class PersonalForm(OrderForm):
    passw  = forms.CharField(  label = u'Пароль',                 required=False, error_messages = rd['passw'],   widget=PasswordInput()) 
    passw2 = forms.CharField(  label = u'Подтверждение пароля',   required=False, error_messages = rd['passw'],   widget=PasswordInput())  

    def clean_passw2(self):
        password1 = self.cleaned_data.get('passw')
        password2 = self.cleaned_data.get('passw2')

        if password1 != password2:
            raise forms.ValidationError(u"Ваши пароли не совпадают")
        return password2


    def submit_pass(self,customer_id):
        c = self.submit(customer_id)
        if self.cleaned_data.get('passw') and self.cleaned_data.get('passw2'):
            c.passw = self.cleaned_data.get('passw2')
            c.save()
        return c


    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_id     = 'id-PersonalForm'
        self.helper.form_action = '/personal/'
        self.helper.add_input(Submit('submit', 'Изменить'))
        super(PersonalForm, self).__init__(*args, **kwargs)






class SubmitForm(forms.Form):
    submit  = forms.BooleanField(label = u'Принять условия') 
    comment = forms.CharField   (label = u'Комментарий',     required=False,  widget=l_w)

    def clean_submit(self):
        if not self.cleaned_data.get('submit'):
            raise forms.ValidationError(u'Вы дожны согласиться с правилами')   
        return self.cleaned_data.get('submit')

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_id = 'id-SubmitForm'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = '/buy/'
        self.helper.add_input(Submit('submit', 'Заказать'))

        super(SubmitForm, self).__init__(*args, **kwargs)

# for good will 
#class ReccomendationForm(forms.Form):
#    price_choice = (
#      (0,"< 1000 р."),
#      (1,"< 10 000 р. "),
#      (2,"< 100 000 р."),
#      (3,"бюджет не ограничен"))#

#    what_for_choice = (
#      (0, 'Подарок'),
#      (1, 'В коллекцию'),
#      (2, 'Другое. Укажу в примечании'))#

#    year_choice = (
#      (0, 'Серебряный век'),
#      (1, 'XIX век и раньше'),
#      (2, 'послереволюционные издания'))#
#

#    price       =  forms.ChoiceField(label = u'Выбирете примерный бюджет', required=False)
#    what_for    =  forms.ChoiceField(label = u'Для чего',                  choices=what_for_choice, required=False)
#    year        =  forms.ChoiceField(label = u'Укажите временные рамки',   choices=what_for_choice, required=False)
#    comment     =  forms.CharField(  label = u'Примечание',                required=False, widget=forms.Textarea)#
#

#    def __init__(self, *args, **kwargs):
#        self.helper = FormHelper()
#        self.helper.form_id = 'id-reccomendationform'
#        self.helper.form_class = 'blueForms'
#        self.helper.form_method = 'post'
#        self.helper.form_action = '/recommend/'
#        self.helper.add_input(Submit('submit', 'Отправить'))#

#        super(SubmitForm, self).__init__(*args, **kwargs)#













class RegisterForm(forms.Form):




    user_type_choice = (
      (0,u'Физическое  лицо'),
      (1,u'Юридическое лицо')) 

    email  = forms.EmailField( label = u'Почта',                  error_messages = rd['email'],   )
    passw  = forms.CharField(  label = u'Пароль',                 error_messages = rd['passw'],   widget=PasswordInput) 
    passw2 = forms.CharField(  label = u'Подтверждение пароля',   error_messages = rd['passw'],   widget=PasswordInput)     

 
    def clean_email(self):
        email = self.cleaned_data.get('email')
        try:
            Customer.objects.get(email=email)
        except Customer.DoesNotExist:
            return email

        raise forms.ValidationError(u'Такой пользователь ужо зарегестрирован')

    def clean_passw2(self):
        password1 = self.cleaned_data.get('passw')
        password2 = self.cleaned_data.get('passw2')

        if not password2:
            raise forms.ValidationError(u"Подтвердите пожалйста пароль")
        if password1 != password2:
            raise forms.ValidationError(u"Ваши пароли не совпадают")
        return password2

    def register(self):
        if not self.is_valid(): return None
        email   = self.cleaned_data.get("email")
        passw   = self.cleaned_data.get("passw")        
        user = Customer(email=email, passw=passw)
        user.save()
        return user

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_id = 'id-RegisterForm'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = '/register/'
        self.helper.add_input(Submit( 'submit', 'Зарегестрироваться'))
        self.helper.layout = Layout( 
            Field('email', placeholder='info@example.ru',css_class='span10'),
            Field('passw', placeholder="password", css_class='span10'),
            Field('passw2',placeholder="password", css_class='span10'),    
            Field('submit',value = u'Зарегестрироваться',css_class='btn')
            )


        super(RegisterForm, self).__init__(*args, **kwargs)






class LoginForm(forms.Form):
    email       = forms.EmailField( label="",  error_messages =rd['email'],           widget=TextInput(attrs={'class':'span9','placeholder':'hi@email.ru'}))
    passw       = forms.CharField(  label="",  error_messages =rd['passw'],           widget=PasswordInput(attrs={'class':'span9', })) 
    other_comp  = forms.BooleanField( label = u'Чужой компьютер', required=False) 

    def clean_passw(self):
        if not self.get_user():
            raise forms.ValidationError(u'Логин или пароль неверны')
        return self.cleaned_data.get('passw')

    def get_user(self):
        email = self.cleaned_data.get('email')
        passw = self.cleaned_data.get('passw')
        try:
            return Customer.objects.get(email=email,passw=passw)
        except Customer.DoesNotExist:
            return None






        

class SearchBlurForm(forms.Form):
    sort_by_choice = ( 
      ('-date' ,u'По дате поступления'),
      ('name'  ,u'По названию А-я'), 
      ('-name' ,u'По названию Я-а'), 
      ('price' ,u'По цене по возрастанию'), 
      ('-price',u'По цене по убыванию'))



    year__gte  = forms.IntegerField( label='',  required=False, error_messages=rd['number'],widget=TextInput(attrs={'class':'span9','placeholder':'1600'}))
    year__lte  = forms.IntegerField( label='',  required=False, error_messages=rd['number'],widget=TextInput(attrs={'class':'span9','placeholder':'1950'}))
    price__gte = forms.IntegerField( label='',  required=False, error_messages=rd['number'],widget=TextInput(attrs={'class':'span9','placeholder':'500'}))    
    price__lte = forms.IntegerField( label='',  required=False, error_messages=rd['number'],widget=TextInput(attrs={'class':'span9','placeholder':'2 000 000'}))
    keywords   = forms.CharField(               required=False, widget=Textarea(attrs={'class':'span12','rows':'2'}))
    category   = TreeNodeChoiceField(           required=False, queryset=Category.objects.all(), widget=Select(attrs = {'class':'span12'}))
    order_by   = forms.ChoiceField(             required=False, choices=sort_by_choice, widget=Select(attrs = {'class':'span12'}))


    def search(self):


        if not self.is_valid(): return False

        ch = lambda k: self.cleaned_data.get(k)

        sqs = SearchQuerySet()

        if  ch('keywords'):
            
            sqs = sqs.auto_query(ch('keywords'))

        if  ch('category'):
            sqs = sqs.filter_and(categories=int(ch('category').pk))
                 
        for i in ['year__gte','year__lte','price__gte','price__lte']: 
            if ch(i):

                chu = {i:ch(i)}
                sqs = sqs.filter_and(**chu)


        if  ch('order_by') and sqs:
            sqs = sqs.order_by(ch('order_by'))


        return sqs








#class companyForm(forms.Form):
#    company_name    = forms.CharField(error_messages = {'required':u'Пожалуйста, укажите название'})
#    company_address = forms.CharField(error_messages = {'required':u'Пожалуйста, укажите адрес'})
#    inn_number      = forms.CharField(error_messages = {'required':u'Пожалуйста, укажите ИНН'})
#    acaunt_one      = forms.CharField(error_messages = {'required':u'Пожалуйста, укажите счет А'})
#    bank_name       = forms.CharField(error_messages = {'required':u'Пожалуйста, укажите имя банка'})
#    accaunt_two     = forms.CharField(error_messages = {'required':u'Пожалуйста, укажите счет 2'})
#    bik_number      = forms.CharField(error_messages = {'required':u'Пожалуйста, укажите БИК'})
#    okpo_number     = forms.CharField(error_messages = {'required':u'Пожалуйста, укажите ОКПО'})
#    okved_number    = forms.CharField(error_messages = {'required':u'Пожалуйста, укажите ОКВЕД'})

class validation(forms.Form):
    number =  forms.IntegerField(required=False)